﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO.Ports;
//using SerialPortHelperLib;
using XChip_Common;
using XChipTool.Enties;
using System.Configuration;
using BinAnalysisHelp;
using System.Threading;
using AdbService;

namespace XChipTool
{
    public partial class XChip_Reg_Cfa : DevExpress.XtraEditors.XtraUserControl
    {
        public SerialPort sPortTemp;
        private bool isRead = false;
        private bool isWrite = false;
        private KeyEventArgs keyEnter = new KeyEventArgs(Keys.Enter);//用来手动触发文本框下发配置
        List<string> listfiltration = new List<string> { "slope", "scale_sig", "scale_enh" };
        //记录是否使用USB设备读写
        public bool IsUsbOpen = false;
        //记录是否使用I2C设备读写
        public bool m_open = false;
        private addressregisterManager aBll;
        private List<addressregister> XChipCfa;
        public parameter_exportManager Pe_dal { get; private set; }
        private string radiostr = string.Empty;

        // 使用服务定位器获取ADB服务
        private IAdbCommandService adbService = ServiceLocator.AdbCommandService;

        public XChip_Reg_Cfa()
        {
            InitializeComponent();
        }
        public XChip_Reg_Cfa(SerialPort _sPortTemp, addressregisterManager _aBll)
        {
            aBll = _aBll;
            XChipCfa = aBll.GetList(c => c.ChipType == ConfigurationManager.AppSettings["xc151_ChipType"] && (c.Classify == "CFA"));
            InitializeComponent();
        }
        private Control[] Controls_Find(string str)
        {
            //var t =   this.Controls.Find(type, true);
            List<Control> listc = new List<Control>();
            System.Reflection.FieldInfo[] fieldInfo = this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
            for (int i = 0; i < fieldInfo.Length; i++)
            {
                if (fieldInfo[i].Name.ToLower().Contains(str.ToLower()))
                {
                    listc.AddRange(this.Controls.Find(fieldInfo[i].Name, true));
                    //break;
                }
            }
            return listc.ToArray();
        }
        private void XChip_Reg_Cfa_Load(object sender, EventArgs e)
        {
            Task.Run(() => {
            this.Invoke((EventHandler)delegate {

              

                for (int i = 0; i < XChipCfa.Count; i++)
                {
                    
                    var type = AppHelper.NameTypeToString(XChipCfa[i].NameType);
                    //加上单选框的_en
                    //if (XChipCfa[i].ControlType == "1")
                    //{
                    //    type = XChipCfa[i].NameType;
                    //}
                    var col = Controls_Find(type);
                    

                    foreach (var item in col)
                    {
                        if (item is TextEdit)
                        {
                            //声明一个SuerToolTip
                            DevExpress.Utils.SuperToolTip graduationBatchSuperToolTip = new DevExpress.Utils.SuperToolTip();
                            //声明一个ToolTipTitleItem,保存标题
                            DevExpress.Utils.ToolTipTitleItem toolTipTitleItem = new DevExpress.Utils.ToolTipTitleItem();
                            String tooltips = "";
                            if (!string.IsNullOrEmpty(XChipCfa[i].Bit_Wide))
                            {
                                tooltips += $"位宽={XChipCfa[i].Bit_Wide}";
                            }
                            if (!string.IsNullOrEmpty(XChipCfa[i].Bit_Accuracy))
                            {
                                tooltips += $"|精度={XChipCfa[i].Bit_Accuracy}";
                            }
                            //设置标题文字
                            toolTipTitleItem.Text = tooltips;
                            //把标题添加到SuerToolTip
                            graduationBatchSuperToolTip.Items.Add(toolTipTitleItem);
                            //指定控件的SuperTip
                            ((TextEdit)item).SuperTip = graduationBatchSuperToolTip;
                            //正则判断
                            ((TextEdit)item).Properties.Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.RegEx;
                            ((TextEdit)item).Properties.Mask.EditMask = BitsHelp.GetBitsToMask(XChipCfa[i].Bits, XChipCfa[i].Bit_Wide, XChipCfa.Where(c => c.NameType.ToLower().Contains(type) && c.ControlType == "0").Select(c => c.Bits).ToList());
                        }
                    }
                }
                });
            });
        }

        private async Task<long> GetCFARegister(string nameType)
        {
            if (XChipCfa.Exists(c => c.NameType.ToLower() == nameType.ToLower()))
            {
                long var = await ReadRegisterAsync(XChipCfa.Where(c => c.NameType.ToLower() == nameType.ToLower()).First().Address);
                return var;
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"未找到{nameType}"); return -1;
            }
        }
        private async Task SetCFARegister(addressregister model, ulong add, bool isCheck = true)
        {
            if (isRead) return;
            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetCFARegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }
        }


        private async void fnr_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var readVal = GetCFARegister("fnr_en");
            //SetCFARegister("fnr_en", (ulong)(fnr_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipCfa.Find(c => c.NameType.ToLower() == $"fnr_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(fnr_en.Checked ? (readVal | 0x01) : (readVal & 0xfe));
            if (isRead) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == $"fnr_en".ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == $"fnr_en".ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), fnr_en.Checked);
                await SetCFARegister(model, Val);
            }
        }

        private async void enh_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var readVal = GetCFARegister("enh_en");
            //SetCFARegister("enh_en", (ulong)(enh_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipCfa.Find(c => c.NameType.ToLower() == $"enh_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(enh_en.Checked ? (readVal | 0x01) : (readVal & 0xfe));
            if (isRead) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == $"enh_en".ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == $"enh_en".ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), enh_en.Checked);
                SetCFARegister(model, Val);
            }
        }

        private void slope_k_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(slope_k.Text))
            {
                //var nHigh = Convert.ToUInt32(slope_k.Text, 16);
                //SetCFARegister("slope_k", (ulong)nHigh);

                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"slope_k".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"slope_k".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, slope_k.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void slope_k_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            slope_k_KeyDown(sender, keyEnter);
        }

        private void slope_b_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(slope_b.Text))
            {
                //var nHigh = Convert.ToUInt32(slope_b.Text, 16);
                //SetCFARegister("slope_b", (ulong)nHigh);

                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"slope_b".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"slope_b".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, slope_b.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void slope_b_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            slope_b_KeyDown(sender, keyEnter);
        }

        private void offset_k_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(offset_k.Text))
            {
                //var nHigh = Convert.ToUInt32(offset_k.Text, 16);
                //SetCFARegister("offset_k", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"offset_k".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"offset_k".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, offset_k.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void offset_k_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            offset_k_KeyDown(sender, keyEnter);
        }

        private void offset_b_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(offset_b.Text))
            {
                //var nHigh = Convert.ToUInt32(offset_b.Text, 16);
                //SetCFARegister("offset_b", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"offset_b".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"offset_b".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, offset_b.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void offset_b_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            offset_b_KeyDown(sender, keyEnter);
        }

        private void fnr_str_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(fnr_str.Text))
            {
                //var nHigh = Convert.ToUInt32(fnr_str.Text, 16);
                //SetCFARegister("fnr_str", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"fnr_str".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"fnr_str".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, fnr_str.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void fnr_str_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            fnr_str_KeyDown(sender, keyEnter);
        }

        private void scale_sig_list_0_KeyDown(object sender, KeyEventArgs e)
        {
            //if (isWrite) return;
            //var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            //if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //SetCFARegister($"scale_sig_list[{txtEdit.Tag.ToString()}]", (ulong)Convert.ToInt32(txtEdit.Text, 16));

            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetCFARegister(model, Val);
            }

        }

        private void scale_sig_list_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sig_list_0_KeyDown(sender, keyEnter);
        }

        private void scale_enh_list_0_KeyDown(object sender, KeyEventArgs e)
        {
            //if (isWrite) return;
            //var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            //if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //SetCFARegister($"scale_enh_list[{txtEdit.Tag.ToString()}]", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetCFARegister(model, Val);
            }

        }

        private void scale_enh_list_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_enh_list_0_KeyDown(sender, keyEnter);
        }

        private void scale_sbl_list_0_KeyDown(object sender, KeyEventArgs e)
        {
            //if (isWrite) return;
            //var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            //if (string.IsNullOrEmpty(txtEdit.Text)) return;
            //SetCFARegister($"scale_sbl_list[{txtEdit.Tag.ToString()}]", (ulong)Convert.ToInt32(txtEdit.Text, 16));
            if (isWrite) return;
            var txtEdit = sender as DevExpress.XtraEditors.TextEdit;
            if (string.IsNullOrEmpty(txtEdit.Text)) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == txtEdit.Name.ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == txtEdit.Name.ToLower());
                var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txtEdit.Text);
                SetCFARegister(model, Val);
            }

        }

        private void scale_sbl_list_0_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sbl_list_0_KeyDown(sender, keyEnter);
        }

        private async void scale_sig_man_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var readVal = GetCFARegister("scale_sig_man_en");
            //SetCFARegister("scale_sig_man_en", (ulong)(scale_sig_man_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipCfa.Find(c => c.NameType.ToLower() == $"scale_sig_man_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(scale_sig_man_en.Checked ? (readVal | 0x01) : (readVal & 0xfe));
            if (isRead) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == $"scale_sig_man_en".ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == $"scale_sig_man_en".ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_sig_man_en.Checked);
                SetCFARegister(model, Val);
            }
            EnShowHide();
        }

        private async void scale_enh_man_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var readVal = GetCFARegister("scale_enh_man_en");
            //SetCFARegister("scale_enh_man_en", (ulong)(scale_enh_man_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipCfa.Find(c => c.NameType.ToLower() == $"scale_enh_man_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(scale_enh_man_en.Checked ? (readVal | 0x01) : (readVal & 0xfe));
            if (isRead) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == $"scale_enh_man_en".ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == $"scale_enh_man_en".ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), scale_enh_man_en.Checked);
                SetCFARegister(model, Val);
            }
            EnShowHide();
        }

        private async void tunning_disp_en_CheckedChanged(object sender, EventArgs e)
        {
            //if (isRead) return;
            //var readVal = GetCFARegister("tunning_disp_en");
            //SetCFARegister("tunning_disp_en", (ulong)(tunning_disp_en.Checked ? (readVal | 0x01) : (readVal & 0xfe)));
            //var readVal = SerialSend.ReadRegister(Convert.ToUInt32(XChipCfa.Find(c => c.NameType.ToLower() == $"tunning_disp_en".ToLower()).Address, 16), sPortTemp);
            //var t = (ulong)(tunning_disp_en.Checked ? (readVal | 0x01) : (readVal & 0xfe));
            if (isRead) return;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == $"tunning_disp_en".ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == $"tunning_disp_en".ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), tunning_disp_en.Checked);
                SetCFARegister(model, Val);
            }
            EnShowHide();
        }

        private void scale_sig_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_sig_man.Text))
            {
                //var nHigh = Convert.ToUInt32(scale_sig_man.Text, 16);
                //SetCFARegister("scale_sig_man", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"scale_sig_man".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"scale_sig_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_sig_man.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void scale_sig_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_sig_man_KeyDown(sender, keyEnter);
        }

        private void scale_enh_man_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(scale_enh_man.Text))
            {
                //var nHigh = Convert.ToUInt32(scale_enh_man.Text, 16);
                //SetCFARegister("scale_enh_man", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"scale_enh_man".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"scale_enh_man".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, scale_enh_man.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void scale_enh_man_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            scale_enh_man_KeyDown(sender, keyEnter);
        }

        private void tunning_disp_sel_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(tunning_disp_sel.Text))
            {
                //var nHigh = Convert.ToUInt32(tunning_disp_sel.Text, 16);
                //SetCFARegister("tunning_disp_sel", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"tunning_disp_sel".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"tunning_disp_sel".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, tunning_disp_sel.Text);
                    if (Convert.ToUInt32(tunning_disp_sel.Text, 16) > Val)
                    {
                        tunning_disp_sel.Text = Val.ToString("X");
                    }
                    SetCFARegister(model, Val);
                }
            }
        }

        private void tunning_disp_sel_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            tunning_disp_sel_KeyDown(sender, keyEnter);
        }

        private void tunning_disp_scale_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !string.IsNullOrEmpty(tunning_disp_scale.Text))
            {
                //var nHigh = Convert.ToUInt32(tunning_disp_scale.Text, 16);
                //SetCFARegister("tunning_disp_scale", (ulong)nHigh);
                if (XChipCfa.Exists(c => c.NameType.ToLower() == $"tunning_disp_scale".ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == $"tunning_disp_scale".ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, tunning_disp_scale.Text);
                    if (Convert.ToUInt32(tunning_disp_scale.Text, 16) > Val)
                    {
                        tunning_disp_scale.Text = Val.ToString("X");
                    }
                    SetCFARegister(model, Val);
                }
            }
        }

        private void tunning_disp_scale_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            tunning_disp_scale_KeyDown(sender, keyEnter);
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void simpleButton5_Click(object sender, EventArgs e)
        {
            WaitBefore.Start("读取中", "正在加载中", 10);
            // 记录开始时间和寄存器计数
            var startTime = DateTime.Now;
            int totalRegisterCount = 0;

            isRead = true;
            long nMask = await GetCFARegister("Scene_Mode") & 0x03;
            if (nMask == 0)
            {
                rdo_scene.SelectedIndex = 0;
                radiostr = "_day";
            }
            else /*if (nMask == 1)*/
            {
                rdo_scene.SelectedIndex = 1;
                radiostr = "_night";
            }
            //else if (nMask == 2)
            //{
            //    AE_radiomode.SelectedIndex = 2;
            //}
            //Scene_Switch_En
            if (( await GetCFARegister("nEffectSceneMode") == 0x12))
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Checked;
                checkedListBoxControl1.Items[1].Enabled = true;
            }
            else
            {
                checkedListBoxControl1.Items[0].CheckState = CheckState.Unchecked;
                checkedListBoxControl1.Items[1].Enabled = false;
                rdo_scene.Enabled = false;
            }
            //Debug_En
            if ((await GetCFARegister("nSwitchMode") & 0x02) == 0x00)
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Checked;
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)
                {
                    rdo_scene.Enabled = true;
                }
            }
            else
            {
                checkedListBoxControl1.Items[1].CheckState = CheckState.Unchecked;
                rdo_scene.Enabled = false;
            }
            isRead = false;


            List<string> NameList = new List<string>();

            for (int i = 0; i < XChipCfa.Count; i++)
            {
                if (XChipCfa[i].NameType.Contains("min_shp"))
                {

                }
                var type = AppHelper.NameTypeToString(XChipCfa[i].NameType);
                if (NameList.Exists(c => c.ToLower() == (type)))
                {
                    continue;
                }
                //加上单选框的_en
                if (XChipCfa[i].ControlType == "1")
                {
                    type = XChipCfa[i].NameType;
                }
                var col = Controls_Find(type);

                foreach (var item in col)
                {
                    if (item is TextEdit)
                    {
                        //过滤掉指定寄存器
                        if (listfiltration.Exists(c => c == col.ToString()))
                        {
                            continue;
                        }

                        var nList = XChipCfa.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.NameType.ToLower().Contains(radiostr) && c.ControlType == "0").ToList();
                        if (nList.Count == 0)
                        {
                            nList = XChipCfa.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "0").ToList();
                        }
                        if (nList.Count == 1)
                        {
                            // 单个寄存器读取
                            var address = nList[0].Address;
                            totalRegisterCount++;
                            await ReadRegisterAndUpdateTextAsync(address, item as TextEdit, nList[0].Bits, nList[0].Hex);
                        }
                        else
                        {
                            // 多个寄存器组合读取
                            totalRegisterCount += nList.Count;
                            await ReadMultipleRegistersAndUpdateTextAsync(nList, item as TextEdit);
                        }
                    }
                    else if (item is CheckEdit)
                    {
                        var nList = XChipCfa.Where(c => c.NameType.ToLower().Contains(item.Name.ToString().ToLower()) && c.ControlType == "1").ToList();
                        if (nList.Count == 1)
                        {
                            var address = nList[0].Address;
                            totalRegisterCount++;
                            await ReadRegisterAndUpdateCheckAsync(address, item as CheckEdit, nList[0].Bits, nList[0].Hex);
                        }
                    }
                    NameList.Add(item.Name);

                }

                //NameList.Add(type);
            }
            isRead = false;
            WaitBefore.Close();
            EnShowHide();


        }

        public async void Get_SlopeOffsetSigmaNr()
        {
            slope.Text = (await GetCFARegister("slope")).ToString("X2");
            offset.Text = ((await GetCFARegister("offset_h")) + await GetCFARegister("offset_l")).ToString("X4");
            scale_sig.Text = (await GetCFARegister("scale_sig")).ToString("X2");
            scale_enh.Text = (await GetCFARegister("scale_enh")).ToString("X2");
            
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            Get_SlopeOffsetSigmaNr();
        }

        private void btn_SaveISPSetting_Click(object sender, EventArgs e)
        {
            
            //SaveFileDialog sfd = new SaveFileDialog();
            ////设置文件类型 
            //sfd.Filter = "配置文件（*.txt）|*.txt";

            ////设置默认文件类型显示顺序 
            //sfd.FilterIndex = 1;

            ////保存对话框是否记忆上次打开的目录 
            //sfd.RestoreDirectory = true;
            //sfd.FileName = "IQ_Setting_CFA_" + DateTime.Now.ToString("yyyyMMddHHmmss");
            //if (sfd.ShowDialog() == DialogResult.OK)
            //{
            //    StringBuilder sb = new StringBuilder();
            //    Pe_dal = new parameter_exportManager();
            //    if (null != Pe_dal)
            //    {
            //        WaitBefore.Start("参数导出", "正在加载中", 60);
            //        //var tempList = Pe_dal.GetList().OrderBy(c => c.SortNum);
            //        var tempList = Pe_dal.GetList(c => c.Module == "CFA").OrderBy(c => c.SortNum).ToList();
                 
            //        sb.Append("0xffff,0xfef1,\n");
            //        sb.Append("\n");
            //        sb.Append($"//{tempList.First().Module}\n");
            //        foreach (var item in tempList)
            //        {
            //            try
            //            {
            //                sb.Append(string.IsNullOrEmpty(item.PreNote) ? "" : "\n" + item.PreNote + "\n");
            //                sb.Append(string.IsNullOrEmpty(item.addr) ? "" : item.addr);
            //                #region 判断是否需要用白天的数据
            //                if (!string.IsNullOrEmpty(item.ReadAddr))
            //                {
                                
            //                    sb.Append($",0x{SerialSend.ReadRegister((Convert.ToUInt32(item.ReadAddr.Trim(), 16)), sPortTemp).ToString("x2")},");
                                
            //                }
            //                #endregion
            //                sb.Append(string.IsNullOrEmpty(item.RearNote) ? "" : item.RearNote = item.RearNote.Replace("\\n", "\n").Replace("\\r", "\r"));
            //                sb.Append("\n");
            //            }
            //            catch (Exception ex)
            //            {
            //                WaitBefore.Close();
                            
            //                DevExpress.XtraEditors.XtraMessageBox.Show(ex.Message);
            //                return;
            //            }
            //        }
            //        System.IO.File.WriteAllText(sfd.FileName, sb.ToString());
            //        WaitBefore.Close();
            //        DevExpress.XtraEditors.XtraMessageBox.Show("参数导出完成");
            //    }
            //}
        }

        private async void checkedListBoxControl1_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            if (isRead) return;

            //Scence Switch En 
            var nTemp1 = GetCFARegister("nEffectSceneMode");
            // Debug en
            var nTemp2 = GetCFARegister("nSwitchMode");
            if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
            {
                //SetCmxRegister("nEffectSceneMode", (ulong)(nTemp1 | 0x04));
                SetCFARegister("nEffectSceneMode", 0x12);
                checkedListBoxControl1.Items[1].Enabled = true;
                if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
                {
                    rdo_scene.Enabled = true;
                }
            }
            else  //S不勾选
            {
                //SetCmxRegister("nEffectSceneMode", (ulong)(nTemp1 & 0xfb));
                SetCFARegister("nEffectSceneMode", 0x00);
                checkedListBoxControl1.Items[1].Enabled = false;
                rdo_scene.Enabled = false;
            }


            if (checkedListBoxControl1.Items[1].CheckState == CheckState.Checked)//D勾选
            {
                SetCFARegister("nSwitchMode", (ulong)(await nTemp2 & 0xfd));
                if (checkedListBoxControl1.Items[0].CheckState == CheckState.Checked)//S勾选
                {
                    rdo_scene.Enabled = true;
                }
            }
            else//D不勾选
            { //

                SetCFARegister("nSwitchMode", (ulong)(await nTemp2 | 0x02));
                rdo_scene.Enabled = false;
            }
        }

        private async void rdo_scene_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var aeradio = sender as DevExpress.XtraEditors.RadioGroup;

            if (aeradio.EditValue.ToString() == "1")
            {
                SetCFARegister("Scene_Mode", 0x00);
                radiostr = "_day";
            }
            else if (aeradio.EditValue.ToString() == "2")
            {
                SetCFARegister("Scene_Mode", 0x01);
                radiostr = "_night";
            }
            //else if (aeradio.EditValue.ToString() == "3")
            //{
            //    SetCFARegister("Scene_Mode", 0x02);
            //}

            Thread.Sleep(50);
            await WriteRegisterAsync(0x80140a8f.ToString("X"), 0x01.ToString("X"));
            simpleButton5_Click(null, null);
        }


        private async Task SetCFARegister(string nameType, ulong add)
        {
            if (isRead) return;
            var model = XChipCfa.Find(c => c.NameType.ToLower() == (nameType).ToLower());
            bool success = await WriteRegisterAsync(model.Address, add.ToString("X"));

            if (!success)
            {
                Console.WriteLine($"[ADBForm] SetCfaRegister 写入失败 - 地址: {model.Address}, 值: {add:X}");
            }



        }

        private async void shp_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), txt.Checked);
                SetCFARegister(model, Val);
            }
        }

        private async void CIP_10_en_CheckedChanged(object sender, EventArgs e)
        {
            if (isRead) return;
            var txt = sender as CheckEdit;
            if (XChipCfa.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
            {
                var model = XChipCfa.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                var Add = await ReadRegisterAsync(model.Address);
                var Val = BitsHelp.SetBitsCheckedToUint(model.Bits, model.Hex, Add.ToString("X2"), txt.Checked);
                SetCFARegister(model, Val);
            }
            EnShowHide();
        }

        private void min_detail_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                if (isRead) return; //判断是否在读，读的时候不进行写           
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipCfa.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetCFARegister(model, Val);
                }
            }
        }

        private void min_detail_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            min_detail_KeyDown(sender, keyEnter);
        }

        private void min_shp_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (isWrite) return;
                if (isRead) return; //判断是否在读，读的时候不进行写           
                var txt = sender as DevExpress.XtraEditors.TextEdit;
                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipCfa.Exists(c => c.NameType.ToLower() == (txt.Name).ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == (txt.Name).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetCFARegister(model, Val);
                }

                if (string.IsNullOrEmpty(txt.Text)) return;
                if (XChipCfa.Exists(c => c.NameType.ToLower() == (txt.Name + radiostr).ToLower()))
                {
                    var model = XChipCfa.Find(c => c.NameType.ToLower() == (txt.Name + radiostr).ToLower());
                    var Val = BitsHelp.SetBitsToUint(model.Bits, model.Hex, txt.Text);
                    SetCFARegister(model, Val);
                }

            }
        }

        private void min_shp_Leave(object sender, EventArgs e)
        {
            if (isWrite) return;
            min_shp_KeyDown(sender, keyEnter);
        }

        private void EnShowHide()
        {
            scale_sig_man.Enabled = scale_sig_man_en.Checked;
            scale_enh_man.Enabled = scale_enh_man_en.Checked;
            tunning_disp_sel.Enabled = tunning_disp_en.Checked;
            tunning_disp_scale.Enabled = tunning_disp_en.Checked;

            cip_noise.Enabled = CIP_10_en.Checked;
            min_shp.Enabled = CIP_10_en.Checked;
            max_shp.Enabled = CIP_10_en.Checked;
            min_detail.Enabled = CIP_10_en.Checked;
            max_detail.Enabled = CIP_10_en.Checked;
            min_shp_gain.Enabled = CIP_10_en.Checked;
            max_shp_gain.Enabled = CIP_10_en.Checked;

            scale_sig_list0.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list1.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list2.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list3.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list4.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list5.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list6.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list7.Enabled = !scale_sig_man_en.Checked;
            scale_sig_list8.Enabled = !scale_sig_man_en.Checked;

            scale_enh_list0.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list1.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list2.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list3.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list4.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list5.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list6.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list7.Enabled = !scale_enh_man_en.Checked;
            scale_enh_list8.Enabled = !scale_enh_man_en.Checked;


        }

        /// <summary>
        /// 异步读取单个寄存器并更新文本框
        /// </summary>
        private async Task ReadRegisterAndUpdateTextAsync(string address, TextEdit textEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");

                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    string processedValue = record.Values;
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    Console.WriteLine($"[ADBForm] 成功读取寄存器 {address} 值: {processedValue}");

                    // 处理位操作
                    string displayValue;
                    if (processedValue != "0")
                    {
                        var uintValue = BitsHelp.GetBitsToUint(bits, hex, processedValue);
                        displayValue = uintValue.ToString("X");
                        Console.WriteLine($"[ADBForm] 寄存器 {address} Bits处理后值: {displayValue} (bits:{bits}, hex:{hex})");
                    }
                    else
                    {
                        displayValue = "0";
                    }

                    // 更新UI
                    UpdateTextEdit(textEdit, displayValue);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    UpdateTextEdit(textEdit, "0");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 异步读取多个寄存器并组合更新文本框
        /// </summary>
        private async Task ReadMultipleRegistersAndUpdateTextAsync(List<addressregister> nList, TextEdit textEdit)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取多个寄存器，数量: {nList.Count}");

                string combinedValue = string.Empty;

                // 按预定义的优先级顺序读取寄存器
                var priorityOrder = new[] { "_h", "_m0", "_m1", "_m2", "_m3", "_l" };

                foreach (var priority in priorityOrder)
                {
                    addressregister register = FindRegisterByPriority(nList, priority);

                    if (register != null)
                    {
                        Console.WriteLine($"[ADBForm] 读取优先级 '{priority}' 的寄存器: {register.NameType} ({register.Address})");

                        // 发送读取命令
                        string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{register.Address},0,0\"";
                        adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{register.Address}");

                        // 等待命令执行
                        await Task.Delay(10);

                        // 获取寄存器值
                        var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(register.Address, "Read", 500));

                        if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                        {
                            string processedValue = record.Values;
                            if (processedValue.StartsWith("0x"))
                            {
                                processedValue = processedValue.Substring(2);
                            }

                            combinedValue += processedValue.PadLeft(2, '0');
                            Console.WriteLine($"[ADBForm] 成功读取 {register.Address}，当前组合值: {combinedValue}");
                        }
                        else
                        {
                            combinedValue += "00";
                            Console.WriteLine($"[ADBForm] 读取 {register.Address} 失败，使用默认值00，当前组合值: {combinedValue}");
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 未找到包含 '{priority}' 的寄存器");
                    }
                }

                Console.WriteLine($"[ADBForm] 最终组合值: {combinedValue}");

                // 更新UI
                UpdateTextEdit(textEdit, combinedValue);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取多个寄存器失败: {ex.Message}");
                UpdateTextEdit(textEdit, "错误");
            }
        }

        /// <summary>
        /// 根据优先级查找寄存器
        /// </summary>
        private addressregister FindRegisterByPriority(List<addressregister> nList, string priority)
        {
            if (priority == "_l")
            {
                // 特殊处理 _l 寄存器
                if (nList.Exists(c => c.NameType.ToLower().Contains("_l")))
                {
                    // 首先查找以 "_l" 结尾的寄存器
                    var exactMatch = nList.Find(c => c.NameType.ToLower().EndsWith("_l"));
                    if (exactMatch != null)
                    {
                        Console.WriteLine($"[ADBForm] 找到以 '_l' 结尾的寄存器: {exactMatch.NameType}");
                        return exactMatch;
                    }
                    else
                    {
                        // 如果没有以 "_l" 结尾的，则使用最后一个包含 "_l" 的寄存器
                        var containsMatch = nList.Last(c => c.NameType.ToLower().Contains("_l"));
                        Console.WriteLine($"[ADBForm] 找到包含 '_l' 的寄存器: {containsMatch.NameType}");
                        return containsMatch;
                    }
                }
            }
            else
            {
                // 其他寄存器正常处理
                var register = nList.Find(c => c.NameType.ToLower().Contains(priority));
                if (register != null)
                {
                    Console.WriteLine($"[ADBForm] 找到包含 '{priority}' 的寄存器: {register.NameType}");
                    return register;
                }
            }

            return null;
        }

        /// <summary>
        /// 更新文本框的辅助方法
        /// </summary>
        private void UpdateTextEdit(TextEdit textEdit, string value)
        {
            if (textEdit.InvokeRequired)
            {
                textEdit.Invoke(new Action(() =>
                {
                    textEdit.Text = value;
                    Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
                }));
            }
            else
            {
                textEdit.Text = value;
                Console.WriteLine($"[ADBForm] UI已更新，文本框值: {value}");
            }
        }

        /// <summary>
        /// 异步读取寄存器并更新复选框
        /// </summary>
        private async Task ReadRegisterAndUpdateCheckAsync(string address, CheckEdit checkEdit, string bits, string hex)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器并更新复选框: {address}");

                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                bool isChecked = false;
                if (!string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    isChecked = BitsHelp.GetBitsCheckedToBool(bits, hex, record.Values) == 0;
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值:{record.Values}, 状态:{isChecked}");
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 复选框更新 - 地址:{address}, 值无效, 状态:false");
                }

                // 更新UI
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = isChecked));
                }
                else
                {
                    checkEdit.Checked = isChecked;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 更新复选框失败: {ex.Message}");
                if (checkEdit.InvokeRequired)
                {
                    checkEdit.Invoke(new Action(() => checkEdit.Checked = false));
                }
                else
                {
                    checkEdit.Checked = false;
                }
            }
        }

        /// <summary>
        /// 异步读取单个寄存器返回值
        /// </summary>
        private async Task<long> ReadRegisterAsync(string address)
        {
            try
            {
                Console.WriteLine($"[ADBForm] 开始读取寄存器: {address}");
                // 发送读取命令
                string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"0,{address},0,0\"";
                adbService.ExecuteAdbCommandAsync(adbCommand, $"读操作 - 地址:{address}");

                // 等待命令执行
                await Task.Delay(10);

                // 获取寄存器值
                var record = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Read", 500));

                if (record != null && !string.IsNullOrEmpty(record.Values) && record.Values != "0")
                {
                    return Convert.ToInt32(record.Values, 16);
                }
                else
                {
                    Console.WriteLine($"[ADBForm] 读取寄存器 {address} 失败，值为空或0，使用默认值0");
                    return 0;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[ADBForm] 读取寄存器 {address} 异常: {ex.Message}");
                return 0;
            }
        }
        /// <summary>
        /// 异步写入单个寄存器，在值不匹配时自动重试一次
        /// </summary>
        private async Task<bool> WriteRegisterAsync(string address, string value)
        {
            int maxRetries = 1; // 值不匹配时最多重试一次
            int retryCount = 0;

            while (retryCount <= maxRetries)
            {
                try
                {
                    if (retryCount > 0)
                    {
                        Console.WriteLine($"[ADBForm] 第 {retryCount} 次重试写入寄存器: {address} 值: {value}");
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 开始写入寄存器: {address} 值: {value}");
                    }

                    // 处理位操作（如果有）
                    string processedValue = value;

                    // 确保值是十六进制格式（不带0x前缀）
                    if (processedValue.StartsWith("0x"))
                    {
                        processedValue = processedValue.Substring(2);
                    }

                    // 发送写入命令
                    string adbCommand = $"adb shell setprop vendor.extcamera.xxw.ispregctrl \"1,{address},{processedValue},0\"";
                    adbService.ExecuteAdbCommandAsync(adbCommand, $"写操作 - 地址:{address} 值:{processedValue}");

                    // 等待命令执行
                    await Task.Delay(10);

                    // 验证写入是否成功 - 等待写入记录出现
                    var writeRecord = await Task.Run(() => LogcatDataManager.FindByRegisterAddressSync(address, "Write", 500));

                    if (writeRecord != null && !string.IsNullOrEmpty(writeRecord.Values))
                    {
                        string actualValue = writeRecord.Values;
                        if (actualValue.StartsWith("0x"))
                        {
                            actualValue = actualValue.Substring(2);
                        }

                        // 比较写入的值是否匹配
                        bool success = string.Equals(actualValue, processedValue, StringComparison.OrdinalIgnoreCase);

                        if (success)
                        {
                            Console.WriteLine($"[ADBForm] 成功写入寄存器 {address} 值: {processedValue}");
                            return true;
                        }
                        else
                        {
                            Console.WriteLine($"[ADBForm] 写入寄存器 {address} 值不匹配，期望: {processedValue}，实际: {actualValue}");

                            // 如果不匹配且还有重试次数，则继续重试
                            if (retryCount < maxRetries)
                            {
                                retryCount++;
                                Console.WriteLine($"[ADBForm] 准备重试写入...");
                                continue; // 直接进入下一次循环，重新发送命令
                            }
                            else
                            {
                                Console.WriteLine($"[ADBForm] 写入寄存器 {address} 重试次数已用完，仍然不匹配");
                                return false;
                            }
                        }
                    }
                    else
                    {
                        Console.WriteLine($"[ADBForm] 写入寄存器 {address} 失败，未找到写入确认记录");

                        // 如果未找到记录且还有重试次数，则重试
                        if (retryCount < maxRetries)
                        {
                            retryCount++;
                            Console.WriteLine($"[ADBForm] 准备重试写入...");
                            continue;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[ADBForm] 写入寄存器 {address} 异常: {ex.Message}");

                    // 如果异常且还有重试次数，则重试
                    if (retryCount < maxRetries)
                    {
                        retryCount++;
                        Console.WriteLine($"[ADBForm] 准备重试写入...");
                        await Task.Delay(10); // 异常后稍作延迟再重试
                        continue;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            return false; // 理论上不会执行到这里
        }
    
    
    
    }
}
